package org.surelink.radius.middleware.acct;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.surelink.radius.cache.OnlineCache;
import org.surelink.radius.middleware.AcctMiddleware;
import org.surelink.radius.model.Ticket;
import org.surelink.radius.model.User;
import org.surelink.radius.model.Online;
import org.surelink.radius.utils.DateTimeUtil;
import org.tinyradius.packet.AccountingRequest;
import java.util.List;


/**
 * 开始记账处理
 */
public class AcctOnOffMiddleware implements AcctMiddleware
{

    private static final Logger logger = Logger.getLogger(AcctOnOffMiddleware.class);

    private static final Logger acctLog = Logger.getLogger("acct");

    @Autowired
    private OnlineCache onlineCache;

    public void onAcct(User user, AccountingRequest request) throws Exception
    {
        int acctype = request.getAcctStatusType();
        if(acctype==AccountingRequest.ACCT_STATUS_TYPE_ACCOUNTING_ON
                || acctype==AccountingRequest.ACCT_STATUS_TYPE_ACCOUNTING_OFF)
        {
            List<Online> olist = onlineCache.getOnlineList();
            for (Online online : olist) {
                Ticket ticket = new Ticket();
                ticket.setUserName(online.getUserName());
                ticket.setAcctSessionId(online.getSessionId());
                ticket.setAcctStartTime(online.getAcctStart());
                ticket.setStartSource(online.getStartSource());

                ticket.setNasIpAddress(online.getClientAddress());
                ticket.setFramedIpAddress(online.getIpAddress());

                // 计算SessionTime
                String stopTime = DateTimeUtil.getDateTimeString();

                int sessionTime = DateTimeUtil.compareSecond(stopTime, online.getAcctStart());
                ticket.setAcctSessionTime(sessionTime);

                ticket.setAcctStopTime(stopTime);
                ticket.setStopSource(acctype);
                acctLog.info(ticket.toTicket());
            }

            String typ = acctype == AccountingRequest.ACCT_STATUS_TYPE_ACCOUNTING_ON ? "开始" : "停止";
            if (logger.isInfoEnabled())
                logger.info(String.format("%s记账处理成功",user.getUserName(),typ));
        }
    }
}
